<template>
  <div id="login-wrap">
    <div class="login-aside">
      <div class="logo" />
      <div class="title" />
    </div>
    <div class="login-content">
      <!-- <div class="login-title">
        <img :src="getLoginLogo()" alt="logo" />
      </div>
      <px-form ref="loginFormRef" class="login-form" :model="loginForm" :rules="loginRules" size="large" label-position="top" @submit.prevent>
        <px-form-item prop="accountName" label="工号">
          <px-input v-model="loginForm.accountName" placeholder="请输入工号">
            <template #prefix>
              <px-icon>
                <UserFilled />
              </px-icon>
            </template>
          </px-input>
        </px-form-item>
        <px-form-item prop="originPassword" label="密码">
          <px-input v-model="loginForm.originPassword" type="password" placeholder="请输入密码" show-password autocomplete="new-password">
            <template #prefix>
              <div class="password-icon" />
            </template>
          </px-input>
        </px-form-item>
        <px-checkbox v-model="remPassword">记住密码</px-checkbox>
        <px-form-item class="login-btn">
          <px-button native-type="submit" size="large" type="primary" :loading="loading" @click="login(loginFormRef)"> 登录 </px-button>
        </px-form-item>
      </px-form> -->
    </div>
  </div>
</template>

<script setup lang="ts">
import { useLayout } from "@/layout/hooks/useLayout";
import { useNav } from "@/layout/hooks/useNav";
import { getTopMenu, initRouter } from "@/router/utils";
import { useUserStoreHook } from "@/store/modules/user";
import axios from "axios";
import type { PxForm } from "px-ui";
import { PxMessage } from "px-ui";
import { onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
const { getLoginLogo } = useNav();
const router = useRouter();
import { getSubSystemUserInfo } from "@/api/user";
// 定义 formRef（校验规则）
type FormInstance = InstanceType<typeof PxForm>;
const loginFormRef = ref<FormInstance>();
const loginRules = reactive({
  accountName: [{ required: true, message: "请输入工号", trigger: "blur" }],
  originPassword: [{ required: true, message: "请输入密码", trigger: "blur" }]
});

const loading = ref(false);
const remPassword = ref();
const loginForm = reactive({
  accountName: "",
  password: "",
  originPassword: "",
  loginType: 1
});
function jsonp(url) {
  return new Promise((resolve, reject) => {
    const callbackName = "jsonp_callback_" + Date.now();
    const script = document.createElement("script");
    script.src = url + (url.indexOf("?") >= 0 ? "&" : "?") + "callback=" + callbackName;
    script.onerror = reject;
    document.body.appendChild(script);

    window[callbackName] = function (data) {
      resolve(data);
      document.body.removeChild(script);
      delete window[callbackName];
    };
  });
}
const { VITE_FANRUAN_BASE_URL } = import.meta.env;
const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid: any) => {
    if (!valid) return;
    loading.value = true;
    try {
      loginForm.password = b64EncodeUnicode(loginForm.originPassword);
      useUserStoreHook()
        .loginByUsername({
          accountName: loginForm.accountName,
          password: loginForm.password,
          loginType: 1
        })
        .then(res => {
          axios({
            method: "get",
            url: "/ifp/account/getSubSystemUserInfo",
            headers: {
              "Content-Type": "application/json",
              Authorization: "Bearer " + res.token,
              facCode: localStorage.getItem("facCode") || ""
            }
          }).then(result => {
            if (result.data.code === 200) {
              if (result.data.data.menuList && result.data.data.menuList.length > 0) {
                const dynamicsMenuList = result.data.data.menuList.filter(item => item.sysCode === "sys-ifp");
                if (dynamicsMenuList && dynamicsMenuList.length > 0) {
                  localStorage.setItem("permissionList", result.data.data.permissionList);
                  localStorage.setItem("userInfo", JSON.stringify(result.data.data.user));
                  // 获取后端路由
                  return initRouter(dynamicsMenuList).then(() => {
                    if (remPassword.value) {
                      const rememberPassword = {
                        accountName: loginForm.accountName,
                        password: loginForm.originPassword,
                        remPassword: remPassword.value
                      };
                      localStorage.setItem("rememberPassword", JSON.stringify(rememberPassword));
                    }
                    router.push(getTopMenu(true).path);
                    PxMessage.success("登录成功！");
                  });
                } else {
                  PxMessage.error("暂无权限，请联系管理员！");
                }
              } else {
                PxMessage.error("暂无权限，请联系管理员！");
              }
              // 后续做帆软单点登录使用
              // let username = encodeURIComponent("ifp_test_user");
              // let password = encodeURIComponent("123456");
              // var url =
              //   VITE_FANRUAN_BASE_URL +
              //   "/webroot/decision/login/cross/domain" +
              //   "?fine_username=" +
              //   username +
              //   "&fine_password=" +
              //   password +
              //   "&validity=" +
              //   -1;
              // console.log(url);
              // jsonp(url)
              //   .then(res => {
              //     if (res.status == "success") {

              //     }
              //   })
              //   .catch(error => {
              //     console.log("报表登录异常");
              //   });
            } else {
              PxMessage.error(result.data.msg);
            }
          });
        })
        .finally(() => (loading.value = false));
    } finally {
      loading.value = false;
    }
  });
};
// UAC方法-密码转为base64方式
const b64EncodeUnicode = (str: string) => {
  return btoa(
    encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function toSolidBytes(_match, p1) {
      return String.fromCharCode(Number("0x" + p1));
    })
  );
};
onMounted(async () => {
  // 检查本地存储中是否有保存的用户名和密码
  // if (localStorage.getItem("rememberPassword")) {
  //   const rememberPassword = JSON.parse(localStorage.getItem("rememberPassword"));
  //   loginForm.accountName = rememberPassword.accountName;
  //   loginForm.originPassword = rememberPassword.password;
  //   remPassword.value = Boolean(rememberPassword.remPassword);
  // } else {
  //   remPassword.value = false;
  // }
  // useLayout().initStorage();

  router.replace({ path: "/" });
});
</script>

<style lang="scss" scoped>
#login-wrap {
  position: relative;
  display: flex;
  align-items: center;
  width: 100%;
  height: 100vh;
  background: url("@/assets/images/login-bg.png");
  background-size: cover;

  .login-aside {
    position: absolute;
    top: 72px;
    left: 98px;

    .logo {
      height: 32px;
      margin-bottom: 18px;
      font-size: 38px;
      font-weight: bold;
      line-height: 32px;
      color: #3b82f6;
    }

    .title {
      height: 24px;
      font-size: 18px;
      line-height: 24px;
      color: #888;
    }
  }

  .login-content {
    position: absolute;
    right: 78px;
    width: 414px;
    height: 503px;
    padding: 66px 42px;
    background-color: #fff;
    border-radius: 6px;
    box-shadow: 0 15px 22px 0 rgb(149 175 224 / 20%);
    transform: translateY(-16px);

    .login-title {
      height: 32px;
      margin-bottom: 66px;
      font-size: 27px;
      font-weight: bold;
      line-height: 32px;
      color: rgb(0 0 0 / 90%);
    }

    .login-form {
      :deep(.px-form-item) {
        margin-bottom: 24px;

        .px-form-item__label {
          height: 21px;
          margin-bottom: 6px;
          font-size: 16px;
          font-weight: bold;
          line-height: 21px;
          color: #000;
        }

        .px-form-item__content {
          .px-input {
            .px-icon {
              font-size: 14px;
              color: #bcbcbc;
            }

            .password-icon {
              width: 10px;
              height: 14px;
              margin-right: 8px;
              margin-left: 2px;
              background: url("@/assets/images/login-password.png");
              background-size: cover;
            }

            .px-input__inner {
              height: 44px;
              font-size: 13px;
              line-height: 44px;
              color: #000;

              &::placeholder {
                font-size: 13px;
                color: #c3c3c3;
              }
            }
          }

          .px-form-item__error {
            font-size: 11px;
          }
        }
      }

      .px-checkbox {
        height: 20px;
        margin-left: 14px;
      }

      .login-btn {
        margin-top: 36px;

        .px-button {
          width: 100%;
          height: 44px;
          font-size: 15px;
          line-height: 44px;
          color: #fff;
        }
      }
    }
  }
}

.login-notification-box {
  &.px-notification {
    .px-notification--success {
      color: var(--px-color-primary);
    }
  }
}
</style>
